﻿using cfg;
using Game.CheseBoard;
using QFramework;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Game.Assets.Scripts.Model
{
    /// <summary>
    /// 棋盘Model
    /// </summary>
    public class ChessModel : AbstractModel
    {
        public const byte ROW = 9;
        public const byte COL = 7;

        Piece[,] chessboard;
        public Piece[,] Chessboard => chessboard;

        public readonly List<Cell> validCell = new List<Cell>();//创建在棋盘上的棋子

        protected override void OnInit()
        {
            chessboard = new Piece[ROW, COL];
        }

        public void SetData(int x, int y, Piece piece)
        {
            chessboard[x, y] = piece;
        }

        /// <summary>
        /// 交换棋子位置
        /// </summary>
        /// <param name="oldLocation"></param>
        /// <param name="newLocation"></param>
        public void OnChangePiecePos((int x, int y) oldLocation, (int x, int y) newLocation)
        {
            Piece temp = chessboard[newLocation.x, newLocation.y];
            chessboard[newLocation.x, newLocation.y] = chessboard[oldLocation.x, oldLocation.y];
            chessboard[oldLocation.x, oldLocation.y] = temp;
            Debug.Log("设置棋子位置");
        }
        /// <summary>
        /// 在棋盘上移除棋子
        /// </summary>
        /// <param name="location"></param>
        public void RemovePiece((int x, int y) location)
        {
            chessboard[location.x, location.y] = null;
            TypeEventSystem.Global.Send(new DestroyPieceEvent() { pos = location });
        }

        /// <summary>
        /// 棋盘是否还有空位
        /// </summary>
        /// <param name="preempt">被预先占用的数量</param>
        /// <returns></returns>
        public bool IsFill(int preempt = 0)
        {
            int emptyNum = 0;
            for (int i = 0; i < chessboard.GetLength(0); i++)
            {
                for (int j = 0; j < chessboard.GetLength(1); j++)
                {
                    if (chessboard[i, j] == null)
                    {
                        emptyNum++;
                    }
                }
            }
            return emptyNum - preempt > 0;
        }

        public void RegisterCell(Cell cell)
        {
            if (!validCell.Contains(cell))
            {
                validCell.Add(cell);
            }
            else
            {
                Debug.LogError("不可重复添加棋子" + cell.name);
            }
        }
        public void UnregisterCell(Cell cell)
        {
            if (validCell.Contains(cell))
            {
                validCell.Remove(cell);
            }
            else
            {
                Debug.LogError("尝试移除一个不存在的棋子" + cell.name);
            }
        }
    }
}